package com.atguigu.flink.chapter02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * TODO wordcount - 批处理 （DataSet API）
 *
 * @author cjp
 * @version 1.0
 * @date 2021/8/6 11:16
 */
public class Flink01_WC_Batch {
    public static void main(String[] args) throws Exception {
        // 0.获取 执行环境
        ExecutionEnvironment benv = ExecutionEnvironment.getExecutionEnvironment();
        // 1.读取数据
        DataSource<String> inputDS = benv.readTextFile("F:\\atguigu\\01_course\\code\\flink210323\\input\\word.txt");

        // 2.处理数据
        // 2.1 压平：切分、转换格式(word,1)
        FlatMapOperator<String, Tuple2<String, Integer>> wordAndOne = inputDS.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                // 切分
                String[] words = value.split(" ");
                // 遍历，每一个元素都发送出去
                for (String word : words) {
                    // 转换成元组
                    Tuple2<String, Integer> tuple2 = Tuple2.of(word, 1);
                    // 通过采集器，一个一个往下游发送
                    out.collect(tuple2);
                }
            }
        });

        // 2.2 按照 word 分组
        UnsortedGrouping<Tuple2<String, Integer>> wordAndOneGroup = wordAndOne.groupBy(0);
        // 2.4 按组聚合
        AggregateOperator<Tuple2<String, Integer>> result = wordAndOneGroup.sum(1);

        // 3.输出（打印）
        result.print();

        // 4.批处理不需要 阻塞、启动


    }
}
